<!-- 权限管理组件 -->
<template>
  <div>
    <!-- 权限管理弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="文档权限管理"
        width="800px"
        :close-on-click-modal="false"
        @close="handleClose"
    >
      <div class="permission-manager-content">
        <!-- 授权表单 -->
        <PermissionGrantForm
            :current-permissions="permissions"
            :document-id="documentId"
            @success="handleGrantSuccess"
            @error="handleGrantError"
            @cancel="internalVisible = false"
        />
      </div>
      <template #footer>
        <el-button @click="closeDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, watch} from 'vue'
import PermissionGrantForm from './PermissionGrantForm.vue'
import {ElMessage} from "element-plus";
import router from "@/router";

interface Props {
  documentId: string
  visible: boolean
}

const props = defineProps<Props>()

const emit = defineEmits(['update:visible'])

// 使用ref来管理内部dialog状态
const internalVisible = ref(props.visible)

// 监听props.visible变化
watch(() => props.visible, (newVal) => {
  internalVisible.value = newVal
})

// 关闭弹窗的处理函数
const closeDialog = () => {
  internalVisible.value = false
  emit('update:visible', false)
}

// 处理弹窗关闭事件（包括点击X和点击遮罩层）
const handleClose = () => {
  emit('update:visible', false)
}

// 计算属性用于双向绑定
const dialogVisible = computed({
  get: () => internalVisible.value,
  set: (value) => {
    internalVisible.value = value
    if (!value) {
      emit('update:visible', false)
    }
  }
})

// 子组件授权成功后的处理
const handleGrantSuccess = () => {
  console.log("success1")
  dialogVisible.value = false; // 关闭弹窗
  ElMessage.success('权限更新成功')
};

const handleGrantError = (error: Error) => {
  // 处理关键错误（如权限不足）
  if (error.message.includes('403')) {
    router.push('/no-permission')
  }
}

const permissions = ref([])

</script>

<style scoped>
.permission-manager-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
}
</style>